package com.zzy.threaddemo.newdemo;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.SettableFuture;

public class AsyncFuntionSample implements AsyncFunction<Long, String> {
	private ConcurrentMap<Long, String> map = Maps.newConcurrentMap();
	private ListeningExecutorService listeningExecutorService;

	public ListenableFuture<String> apply(final Long input) throws Exception {
		if (map.containsKey(input)) {
			
			//SettableFuture可以用来设置要返回得值：
			SettableFuture<String> listenableFuture = SettableFuture.create(); //构建一个SettableFuture
			listenableFuture.set(map.get(input));
			return listenableFuture;
		} else {
			return listeningExecutorService.submit(new Callable<String>() {
				public String call() throws Exception {
					String retrieved = "success";//compute to get the data;
					map.putIfAbsent(input, retrieved);
					return retrieved;
				}
			});
		}
	}
}